<?php
/**
 * 管理员缓存类
 * panglishan
 * 2020.08.13
 */
namespace App\Services\Cache;

use Illuminate\Support\Facades\Cache;   //引入基础缓存类
use App\Exceptions\BasicException;     //引入异常处理类

class AdminCacheService{

    const Admin_Permission = 'admin_permission';  //管理员权限数据缓存标记
    const AdminCacheTime = 1440;    //缓存时间24小时
    const Admin_Menu = 'menu_data';
    const Admin_Menu_Permission = 'menu_permission_data';
    const All_Permission = 'permission_data';


    //缓存管理员的权限数组
    static function cacheAdminPermission($admin_id,$permissionArr)
    {
        if(Cache::tags(self::Admin_Permission)->has($admin_id)) {
            Cache::tags(self::Admin_Permission)->forget($admin_id);
        }

        Cache::tags(self::Admin_Permission)->put($admin_id,json_encode($permissionArr),self::AdminCacheTime);

        return $permissionArr;
    }

    //缓存菜单数据
    static function delCache($name)
    {
        Cache::forget($name);
    }

    //缓存菜单数据
    static function cacheMenuData($data)
    {
        Cache::add(self::Admin_Menu,$data, 60);

        return $data;
    }


    //缓存菜单权限数据
    static function cacheMenuPermissionData($data)
    {
        Cache::add(self::Admin_Menu_Permission,$data, 60);

        return $data;
    }


    //缓存所有权限ID数组
    static function cacheAllPermission($data)
    {
        Cache::add(self::All_Permission,$data, 60);

        return $data;
    }


    //获得后台缓存数据的方法
    static function getCacheData($tag)
    {
        if(!in_array($tag,[self::Admin_Menu,self::Admin_Menu_Permission,self::All_Permission])) throw new BasicException(20061);

        if(!Cache::has($tag)) {
            //没有该缓存数据就去查询
            switch ($tag) {
                case self::Admin_Menu:
                    $data = app('repo_permission')->getAllMenu();
                    self::cacheMenuData($data);
                    break;
                case self::Admin_Menu_Permission:
                    $data = app('repo_permission')->getAllPermission();
                    self::cacheMenuPermissionData($data);
                    break;
                default:
                    $data = app('repo_permission')->getPermissionIDArr();
                    self::cacheAllPermission($data);
            }
            return $data;
        } else {
            return Cache::get($tag);
        }
    }



    //根据管理员ID获取缓存的权限数据
    static function getAdminCache($admin_id)
    {
        if(!Cache::tags(self::Admin_Permission)->has($admin_id)) {
            throw new BasicException(10007);
        }

        return json_decode(Cache::tags(self::Admin_Permission)->get($admin_id), 1);
    }



}